package com.tommy.jiami.ui.dialog;

import android.os.*;
import android.view.*;
import com.tommy.jiami.*;
import android.widget.*;
import android.preference.*;
import android.content.*;
import android.text.*;
import com.tommy.jiami.utils.*;

public class CryptDialog extends BaseDialogFragment
{
	View view;
	EditText password;
	CheckBox isDeleteBox;
	SharedPreferences prefs;
	String path;
	int type;
	TextView text;
	String typeStr;
	
	public CryptDialog(String filePath,int cryptType){
		path=filePath;
		type=cryptType;
	}
	
	@Override
	public View getContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		typeStr = type==Crypt.TYPE_ENCRYPT?"加":"解";
		getDialog().setTitle(getString(R.string.file_dialog_title,typeStr));
		initViews(inflater);
		initListeners();
		return view;
	}
	
	public void initViews(LayoutInflater inflater){
		prefs=PreferenceManager.getDefaultSharedPreferences(getActivity());
		view=inflater.inflate(R.layout.dialog_file,null);
		password=(EditText)view.findViewById(R.id.file_dialog_password);
		isDeleteBox=(CheckBox)view.findViewById(R.id.file_dialog_isdeletebox);
		text=(TextView)view.findViewById(R.id.file_dialog_path);
		isDeleteBox.setChecked(prefs.getBoolean("isDelete"+type,true));
		text.setText(getString(R.string.file_dialog_path,path,typeStr));
		isDeleteBox.setText(getString(R.string.file_dialog_box,typeStr));
		password.setHint(getString(R.string.file_dialog_hint,typeStr));
	}
	
	public void initListeners(){
		isDeleteBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
			public void onCheckedChanged(CompoundButton btn,boolean isChecked)
			{
				prefs.edit()
				.putBoolean("isDelete"+type,isChecked)
				.commit();
			}
		});
	}

	@Override
	protected void onPositiveButtonClick()
	{
		String text=password.getText().toString();
		String pwdStr=TextUtils.isEmpty(text)?
			Utils.getUserPassword():text;
		boolean isDelete=isDeleteBox.isChecked();
		switch(type){
			case Crypt.TYPE_ENCRYPT:
				Crypt.encryptFileWithDialog(getActivity(),path,path+".jiami",pwdStr,isDelete);
				break;
			case Crypt.TYPE_DECRYPT:
				Crypt.decryptFileWithDialog(getActivity(),path,path.substring(0,path.length()-6),pwdStr,isDelete);
				break;
		}
		super.onPositiveButtonClick();
	}	
	
}
